package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-03-11
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private IAlertDataService alertDataService;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     *  设备运维人员角色
     */
    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    /**
     *  管理员角色
     */
    @Value( "${alert.managerRole}")
    private String managerRole;



    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    @Override
    public void alertFilter() {
        //查询所有规则
        Long count = this.lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (count<=0){
            return;
        }
        //获取所有上报数据
        List values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)){
            return;
        }
        ArrayList<DeviceData> list = new ArrayList<>();
        values.forEach(v ->{
            list.addAll(JSONUtil.toList(v.toString(), DeviceData.class));
            //遍历规则

            list.forEach(data-> alertFilterRule(data,LocalDateTime.now()));
        } );
    }

    /**
     *  逐条过滤报警数据
     */
    private void alertFilterRule(DeviceData deviceData ,LocalDateTime now) {
      //判断上报数据是否超过1分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime,now, ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
         //查询所有的该产品规则和该物模型的规则
        //查询全部设备
        List<AlertRule> allRules = this.lambdaQuery().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, "-1").list();
        //查询该设备下的规则
        List<AlertRule> rules = this.lambdaQuery().eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId()).list();
        //合并规则
        Collection<AlertRule> alertRules = CollUtil.addAll(allRules, rules);
        if (CollUtil.isEmpty(alertRules)){
            return;
        }
        //遍历规则
        alertRules.forEach(rule -> {
            deviceDataAlarmHandler(rule,deviceData);
        });
    }

    /**
     *  设备数据处理
     * @param rule
     * @param deviceData
     */
    private void deviceDataAlarmHandler(AlertRule rule, DeviceData deviceData) {
        //1.判断是否在生效时间
        String[] alertTime = rule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(alertTime[0]);
        LocalTime endTime = LocalTime.parse(alertTime[1]);
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        if (alarmTime.toLocalTime().isBefore(startTime) || alarmTime.toLocalTime().isAfter(endTime)){
            return;
        }
        //2.判断数据是否达到阈值
        //获取数据值
        Double dataValue = Double.valueOf(deviceData.getDataValue());
        //获取规则值
        Double ruleValue = rule.getValue();
        //0 等于  1 大于  -1 小于
        int compare = Double.compare(dataValue, ruleValue);
        //定义
        String aggCountKey=CacheConstants.ALERT_KEY_COUNT+deviceData.getIotId()+deviceData.getFunctionId()+":"+rule.getId();
        if ((">=".equals(rule.getOperator())&&compare>=0)
                || ("<".equals(rule.getOperator())&&compare<0 )){
         log.info("数据大于等于阈值");
        }else {
            redisTemplate.delete(aggCountKey);
            return;
        }
        //3.判断是否达到持续周期
        String alertSilentKey= CacheConstants.ALERT_SILENCE_CYCLE+deviceData.getIotId()+rule.getFunctionId()+":"+rule.getId();
        String alertSilent = (String) redisTemplate.opsForValue().get(alertSilentKey);
        if (StrUtil.isNotEmpty(alertSilent)){
            return;
        }
        //获取当前报警次数
        Integer count = (Integer) redisTemplate.opsForValue().get(aggCountKey);
        count= ObjectUtil.isEmpty(count) ? 1 : count+1;
        if (!ObjectUtil.equals(count,rule.getDuration())){
            redisTemplate.opsForValue().set(aggCountKey,count);
            return;
        }
        //删除报警数据
        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(alertSilentKey,"alertSilen",rule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //发送报警信息
        List<Long> userIds = new ArrayList<>();
        //老人异常数据
        if (rule.getAlertDataType()==0){

            if (deviceData.getLocationType().equals(0)){
                //随身设备
                 userIds= deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            }else {
                // 床
                userIds= deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        }else {
            // 设备异常数据
            userIds = sysUserRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }
        List<Long> managerIds = sysUserRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds).stream().distinct().filter(ObjectUtil::isNotNull).collect(Collectors.toList());
        //批量添加报警数据
        insertAlertDate(allUserIds,deviceData,rule);
        AlertNotifyVo alertNotifyVo =BeanUtil.toBean(deviceData, AlertNotifyVo.class);
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setNotifyType(1);
        if (deviceData.getLocationType()==1&&deviceData.getPhysicalLocationType()==2){
            alertNotifyVo.setIsAllConsumer(true);
        }else {
            alertNotifyVo.setIsAllConsumer(false);
        }
        //发送通知
        webSocketServer.sendMessageToConsumer(alertNotifyVo,allUserIds);


    }

    /**
     * 批量添加报警数据
     * @param allUserIds
     * @param deviceData
     * @param rule
     */
    private void insertAlertDate(Collection<Long> allUserIds, DeviceData deviceData, AlertRule rule) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        String alertReason = rule.getFunctionName()+rule.getOperator()+rule.getValue()+rule.getDuration();
        alertData.setAlertReason(alertReason);
        alertData.setType(rule.getAlertDataType());
        alertData.setStatus(0);
        //遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData AlertDatas = BeanUtil.toBean(alertData, AlertData.class);
            AlertDatas.setUserId(userId);
            AlertDatas.setId(null);
            return AlertDatas;
        }).collect(Collectors.toList());
        //批量插入
        alertDataService.saveBatch(list);
    }
}
